#include "StdAfx.h"
#include <wx/collpane.h>
#include <engine/Map.hpp>
#include <engine/MapRenderer.hpp>
#include "wxOgre.h"
#include "ControlPanel.hpp"
#include "MainFrame.hpp"

namespace he
{
	BEGIN_EVENT_TABLE(MainFrame, wxFrame)
		EVT_MENU(ID_Quit, MainFrame::on_quit)
		EVT_MENU(ID_WIREFRAME, MainFrame::on_wireframe)
		EVT_MENU(ID_NOISE, MainFrame::on_noise)
		EVT_MENU(ID_EXPORT, MainFrame::OnMapExport)
		EVT_COLLAPSIBLEPANE_CHANGED(wxID_ANY, MainFrame::on_collapse_event)
//		EVT_MENU(ID_About, MyFrame::OnAbout)
	END_EVENT_TABLE()

	MainFrame::MainFrame()
		: wxFrame(nullptr, -1, "Editor", wxDefaultPosition, wxSize(900, 800)), m_pOgre(new wxOgre(this))
	{
		// Load all image handlers
		wxInitAllImageHandlers();
		m_Manager.SetManagedWindow(this);
		// Create menu
		wxMenu *menuFile = new wxMenu;
		menuFile->Append(ID_EXPORT, "Export");
		menuFile->AppendSeparator();
		menuFile->Append(ID_Quit, "E&xit");
		// Create menu bar
		wxMenuBar *menuBar = new wxMenuBar;
		menuBar->Append(menuFile, _T("&File"));
		// Set main menu
		SetMenuBar(menuBar);
		// Create toolbar
		wxToolBar *p_tool_bar = CreateToolBar();
		// Add toolbar icons
		{
			wxBitmap icon;
			icon.LoadFile("icons/1.png", wxBITMAP_TYPE_PNG);
			p_tool_bar->AddCheckTool(ID_WIREFRAME, "Wireframe", icon);
			// Create noise icon and enable it
			p_tool_bar->AddCheckTool(ID_NOISE, "Noise", icon);
			p_tool_bar->ToggleTool(ID_NOISE, true);
		}
		// Refresh toolbar
		p_tool_bar->Realize();
		// Add wxOgre
		m_Manager.AddPane(m_pOgre, wxCENTER, wxT("Ogre Pane"));
		// Add control panel
		m_pControlPanel = new ControlPanel(this, m_pOgre->TerrainDirector());
		m_Manager.AddPane(m_pControlPanel, wxAuiPaneInfo().CloseButton(true).Caption(wxT("Control Panel")).Left().MinSize(wxSize(200, 500)));
		m_Manager.Update();
	}

	MainFrame::~MainFrame()
	{
		m_Manager.UnInit();
	}

	void MainFrame::on_quit(wxCommandEvent& event)
	{
		Close(true);
	}

	void MainFrame::on_wireframe(wxCommandEvent& Event)
	{
		m_pOgre->show_wireframe(Event.IsChecked());
		m_pOgre->update();
	}

	void MainFrame::on_noise(wxCommandEvent& Event)
	{
		m_pOgre->enable_noise(Event.IsChecked());
		m_pOgre->update();
	}

	void MainFrame::on_collapse_event(wxCollapsiblePaneEvent& Event)
	{
		wxCollapsiblePane *p_pane = static_cast<wxCollapsiblePane *>(Event.GetEventObject());
		// Must set the new size of control panel
		wxSize size = m_pControlPanel->GetBestSize();
		m_Manager.GetPane(m_pControlPanel).MinSize(size);
		m_Manager.Update();
	}

	void MainFrame::OnMapExport(wxCommandEvent &Event)
	{
		std::ofstream out("map.txt");
		m_pOgre->get_map().export_map(out);
	}
}
